<template>
  <div class="item-one" ref="itemOne">
    <div class="title">
      <span>全部商户</span>
      <div>
        <el-button type="primary" disabled>切换</el-button>
        <el-button type="primary" @click="addmerchants()">新增商户</el-button>
        <el-button type="primary">导出</el-button>
        <el-button icon="el-icon-refresh" @click="refresh()"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem" v-if="userinfo.rolesId != 4">
            <el-form ref="conditions" :model="conditions">
              <el-select
                v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8"
                class="servicelevel"
                v-model="conditions.servicelevel"
                placeholder="服务商级别"
                @change="servicelevel"
              >
                <el-option keys="1" label="一级服务商" value="1"></el-option>
                <el-option keys="2" label="二级服务商" value="2"></el-option>
              </el-select>

              <el-autocomplete
                v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2"
                class="servicename"
                v-model="conditions.servicename"
                :fetch-suggestions="querySearch"
                placeholder="服务商名称"
                @select="serviceid"
              ></el-autocomplete>
              <el-autocomplete
                class="BDname"
                v-model="conditions.BDname"
                :fetch-suggestions="BDname"
                placeholder="业态"
                @select="BDid"
              ></el-autocomplete>
            </el-form>
          </div>
          <div class="leftitem">
            <el-form ref="conditions" :model="conditions" label-width="80px">
              <el-select v-model="conditions.merchantsstate" placeholder="商户状态">
                <el-option keys="3" label="启用" value="0"></el-option>
                <el-option keys="4" label="停用" value="98"></el-option>
              </el-select>
              <el-input
                class="merchants"
                v-model="conditions.merchantsno"
                @keyup.enter.native="soso"
                placeholder="商户简称/商户名称/商户号"
              ></el-input>
            </el-form>
          </div>
          <div class="leftitem">
            <el-form label-width="80px">
              <el-select v-model="wx1code" placeholder="行业" @change="wx2fun">
                <el-option
                  v-for="(value, index) in wx1arr"
                  :key="index"
                  :label="value.firstname"
                  :value="value.id"
                ></el-option>
              </el-select>
              <el-select v-model="conditions.wx1s" placeholder="细分行业">
                <el-option
                  v-for="(value, index) in wx2arr"
                  :key="index"
                  :value="value.id"
                  :label="value.secondname"
                ></el-option>
              </el-select>
            </el-form>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem">
            <el-form ref="conditions" :model="conditions" label-width="80px">
              <el-select v-model="conditions.province" placeholder="所在省" @change="city">
                <el-option
                  v-for="(item, index) in provincearr"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                  :codeid="item.id"
                ></el-option>
              </el-select>
              <el-select v-model="conditions.city" placeholder="所在市">
                <el-option
                  v-for="(value, index) in cityarr"
                  :key="index"
                  :label="value.name"
                  :value="value.code"
                ></el-option>
              </el-select>
            </el-form>
          </div>
          <div class="rightitem">
            <div class="block">
              <el-date-picker
                v-model="date"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </div>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="soso">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>
      <div class="statistical">
        <div class="statisticalitem">
          <div>总商户数</div>
          <div>
            <span class="red">{{merchantsinfo.total}}</span> 家
          </div>
        </div>
        <div class="statisticalitem">
          <div>动销商户数</div>
          <div>
            <span class="red">{{merchantsinfo.active}}</span> 家
          </div>
        </div>
      </div>
      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="merchantarr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="center" type="index" label="序号"></el-table-column>
          <el-table-column
            label="商户号?商户简称/商户名"
            width="240"
            align="center"
            :render-header="renderheader"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.merchantNo}}</div>
              <div>{{ scope.row.merchantShortName }}/{{scope.row.merchantName}}</div>
            </template>
          </el-table-column>
          <el-table-column label="所在省?所在市" width="80" align="center" :render-header="renderheader">
            <template slot-scope="scope">
              <div>{{scope.row.merchantProvince}}</div>
              <div>{{scope.row.merchantCity}}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="业态?服务商"
            align="center"
            :render-header="renderheader"
          >
            <template slot-scope="scope">
              <div>{{scope.row.bdName}}</div>
              <div>{{scope.row.agent2Name}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="使用通道" align="center" :render-header="renderheader">
            <template slot-scope="scope">
              <div>微信-{{scope.row.wxChannelName}}</div>
              <div>支付宝-{{scope.row.aliChannelName}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="merchantMccName" label="所属行业" align="center"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
          <el-table-column label="商户状态" width="80" align="center">
            <template slot-scope="scope">
              <div class="green" v-if="scope.row.status == 0">启用</div>
              <div class="red" v-else >停用</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="140">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="joinmerchantsinfo(scope.row.id)"
                :valu="scope.row.merchantNo"
              >详情</el-button>
              <el-button
                type="text"
                size="small"
                @click="addshop(scope.row.merchantShortName,scope.row.id)"
              >新增门店</el-button>
              <el-button
                v-if="scope.row.status == 0"
                type="text"
                size="small"
                @click="blockups(scope.row.id)"
              >停用</el-button>
              <el-button v-else type="text" size="small" @click="merchantenable(scope.row.id)">启用</el-button>
              <el-button type="text" size="small" @click="merchantremove(scope.row.id)">注销</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :current-page.sync="cur_page"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
          ></el-pagination>
        </div>
      </div>
      <br>
      <br>
      <!-- 新增门店 -->
      <el-dialog
        v-dialogDrag
        title="新增门店"
        :visible.sync="visible"
        width="45%"
        :close-on-click-modal="false"
      >
        <el-form
          :model="addmendian"
          status-icon
          ref="addmendian"
          label-width="110px"
          class="demo-dynamic"
        >
          <el-form-item label="所属商户">{{shopname}}</el-form-item>
          <el-form-item :required="true" label="门店名称">
            <el-input type="text" v-model="addmendian.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="门店电话">
            <el-input type="text" v-model="addmendian.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="门店地址">
            <el-input type="text" v-model="addmendian.address" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="联系人">
            <el-input type="text" v-model="addmendian.contact" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="联系人手机号">
            <el-input type="text" v-model="addmendian.contactphone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="银联终端号">
            <el-input type="text" v-model="addmendian.bank" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <!-- @click="visible = false" -->
          <el-button type="primary" @click="addshopfun()">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getservice,
  getBD,
  province,
  city,
  wx1,
  wx2,
  merchantlist,
  getActiveCount,
  addshop,
  blockup,
  merchantremove,
  merchantenable
} from "@/api/api";
export default {
  data: function() {
    return {
      tableData: [],
      cur_page: 1,
      cur_size: 10,
      multipleSelection: [],
      visible: false,
      loading: true,
      servicearr: [],
      BDarr: [],
      provincearr: [],
      cityarr: [],
      wx1arr: [],
      wx1code: "",
      wx2arr: "",
      merchantarr: [],
      combined: 10,
      pageCount: "",
      merchantsinfo: "",
      shopname: "",
      shopid: "",
      date: "",
      addmendian: {
        name: "",
        phone: "",
        address: "",
        contact: "",
        contactphone: "",
        bank: ""
      },
      conditions: {
        servicelevel: "",
        servicename: "",
        BDname: "",
        merchantsstate: "",
        merchantsno: "",
        province: "",
        provincecode: "",
        city: "",
        stardate: "",
        enddate: "",
        serviceid: "",
        BDid: "",
        wx1s: ""
      },
      userinfo: {}
    };
  },
  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));

    // 根据角色区别模糊搜索内容
    if (this.userinfo.rolesId == 2 || this.userinfo.rolesId == 3) {
      getservice({
        type: 2,
        parentid: this.userinfo.fid
      }).then(res => {
        // console.log(res);
        for (var i = 0; i < res.data.rows.length; i++) {
          this.servicearr.push({
            value: res.data.rows[i].agentname,
            id: res.data.rows[i].id
          });
        }
      });
      this.getBD(this.userinfo.fid);
    } else {
      this.getBD();
    }
    this.province();
    this.wx1();
    this.merchantlist();
    if(this.userinfo.rolesId == 2){
      this.conditions.servicelevel == 2
    }else if(this.userinfo.rolesId == 1){  
       this.conditions.servicelevel == 1
    }
  },
  methods: {
    //修改thead 背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
      }
    },
    // 刷新
    refresh() {
      // this.$router.replace({
      //   path: "/refresh",
      //   query: {
      //     t: Date.now()
      //   }
      // });
      this.loading = true;
      this.merchantlist(this.conditions.servicelevel);
    },
    onSubmit() {
      this.$message.success("提交成功！");
    },
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("?")[0]),
        h("br"),
        h("span", {}, column.label.split("?")[1])
      ]);
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.merchantlist(this.conditions.servicelevel);
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    // 分页数量
    sizechange(val) {
      this.cur_size = val;

      this.merchantlist(this.conditions.servicelevel);

      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    //多选框
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
    },
    joinmerchantsinfo(val) {
      // console.log(val)
      this.$router.push({
        path: "/merchantsinfo",
        query: {
          no: val
        }
      });
    },
    //  重置
    reset() {
      this.date = "";
      this.conditions.servicelevel = "";
      this.conditions.servicename = "";
      this.conditions.BDname = "";
      this.conditions.merchantsstate = "";
      this.conditions.merchantsno = "";
      this.conditions.province = "";
      this.conditions.provincecode = "";
      this.conditions.city = "";
      this.conditions.stardate = "";
      this.conditions.enddate = "";
      this.conditions.serviceid = "";
      this.conditions.BDid = "";
      this.conditions.wx1s = "";
      this.wx1code = "";
      this.cur_page = 1;
    },
    // 搜索
    soso() {
      this.cur_page = 1;
      this.loading = true;
      if (this.conditions.servicelevel == 1) {
        this.merchantlist("1");
      } else if (this.conditions.servicelevel == 2) {
        this.merchantlist("2");
      } else {
        this.merchantlist("2");
      }
    },
    // 服务商名称
    querySearch(queryString, cb) {
      let servicearr = this.servicearr;
      let results = queryString
        ? servicearr.filter(this.createFilter(queryString))
        : servicearr;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // 业态
    BDname(queryString, cb) {
      let BDarr = this.BDarr;
      let results = queryString
        ? BDarr.filter(this.createFilter(queryString))
        : BDarr;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    BDid(item) {
      this.conditions.BDid = item.id;
    },
    serviceid(item) {
      this.conditions.serviceid = item.id;
      this.getBD(item.id);
    },
    // 服务商级别
    servicelevel(val) {
      this.servicearr = [];
      getservice({
        type: val
      }).then(res => {
        console.log(res);
        for (var i = 0; i < res.data.rows.length; i++) {
          this.servicearr.push({
            value: res.data.rows[i].agentname,
            id: res.data.rows[i].id
          });
        }
      });
    },
    // 获取BD
    getBD(id) {
      this.BDarr = [];
      getBD({ agentid: id }).then(res => {
        console.log(res);
        for (var i = 0; i < res.data.rows.length; i++) {
          this.BDarr.push({
            value: res.data.rows[i].name,
            id: res.data.rows[i].id
          });
        }
      });
    },
    //获取省
    province() {
      province().then(res => {
        // console.log(res);
        this.provincearr = res.data;
      });
    },
    //获取市
    city(val) {
      let obj = {};
      obj = this.provincearr.find(item => {
        //这里的userList就是上面遍历的数据源
        return item.id === val; //筛选出匹配数据
      });
      console.log(obj);
      this.conditions.provincecode = obj.code;
      this.cityarr = "";
      city({
        provinceId: val
      }).then(res => {
        // console.log(res);
        this.cityarr = res.data;
      });
    },
    // 获取行业
    wx1(val) {
      wx1().then(res => {
        this.wx1arr = res.data;
      });
    },
    // 行业二级
    wx2fun(val) {
      this.wx2arr = "";
      wx2({
        wx1Id: val
      }).then(res => {
        // console.log(res);
        this.wx2arr = res.data;
      });
    },
    // 商户列表
    merchantlist(level) {
      let sosolist = {};
      if (level == 1) {
        sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          agent1Id: this.conditions.serviceid,
          bdId: this.conditions.BDid,
          startTime: this.date[0],
          finishTime: this.date[1],
          cityCode: this.conditions.city,
          merchantMcc2: this.conditions.wx1s,
          provinceCode: this.conditions.provincecode,
          keywords: this.conditions.merchantsno,
          status: this.conditions.merchantsstate
        };
      } else if (level == 2) {
        sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          agent2Id: this.conditions.serviceid,
          bdId: this.conditions.BDid,
          startTime: this.date[0],
          finishTime: this.date[1],
          cityCode: this.conditions.city,
          merchantMcc2: this.conditions.wx1s,
          provinceCode: this.conditions.provincecode,
          keywords: this.conditions.merchantsno,
          status: this.conditions.merchantsstate
        };
      }else{
         sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          bdId: this.conditions.BDid,
          startTime: this.date[0],
          finishTime: this.date[1],
          cityCode: this.conditions.city,
          merchantMcc2: this.conditions.wx1s,
          provinceCode: this.conditions.provincecode,
          keywords: this.conditions.merchantsno,
          status: this.conditions.merchantsstate
        };
      }
      merchantlist(sosolist).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.merchantarr = res.data;
          this.combined = res.pageInfo.recordCount;
          this.pageCount = res.pageInfo.pageCount;
          this.loading = false;
        }
      });
      getActiveCount(sosolist).then(res => {
        console.log(res);
        this.merchantsinfo = res.data;
      });
    },
    // 动销商户
    // getActiveCount(level) {
    //   let sosolist = {};
    //   if (level == 1) {
    //     sosolist = {
    //       page: this.cur_page,
    //       size: this.cur_size,
    //       agent1Id: this.conditions.serviceid,
    //       bdId: this.conditions.BDid,
    //       startTime: this.date[0],
    //       finishTime: this.date[1],
    //       cityCode: this.conditions.city,
    //       merchantMcc2: this.conditions.wx1s,
    //       provinceCode: this.conditions.provincecode,
    //       keywords: this.conditions.merchantsno,
    //       status: this.conditions.merchantsstate
    //     };
    //   } else if (level == 2) {
    //     sosolist = {
    //       page: this.cur_page,
    //       size: this.cur_size,
    //       agent2Id: this.conditions.serviceid,
    //       bdId: this.conditions.BDid,
    //       startTime: this.date[0],
    //       finishTime: this.date[1],
    //       cityCode: this.conditions.city,
    //       merchantMcc2: this.conditions.wx1s,
    //       provinceCode: this.conditions.provincecode,
    //       keywords: this.conditions.merchantsno,
    //       status: this.conditions.merchantsstate
    //     };
    //   }
    //   getActiveCount(sosolist).then(res => {
    //     console.log(res);
    //     this.merchantsinfo = res.data;
    //   });
    // },
    // 打开增加门店
    addshop(val, id) {
      this.visible = true;
      this.shopname = val;
      this.shopid = id;
      this.addmendian.name = "";
      this.addmendian.phone = "";
      this.addmendian.address = "";
      this.addmendian.contact = "";
      this.addmendian.contactphone = "";
      this.addmendian.bank = "";
    },
    // 增加门店
    addshopfun() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      addshop({
        merchantId: this.shopid,
        shopName: this.addmendian.name,
        shopTel: this.addmendian.phone,
        shopAddress: this.addmendian.address,
        managerName: this.addmendian.contact,
        managerMobile: this.addmendian.contactphone,
        terminalNoUni: this.addmendian.bank,
        userId : 1,
        instno: sessionStorage.getItem("instNo"),
        key: sessionStorage.getItem("key")
      }).then(res => {
        if (res.code == 200) {
          loading.close();
          this.$message({
            message: "新增成功",
            type: "success"
          });
          this.visible = false;
          this.refresh();
        } else {
          this.$message.error(res.message);
          loading.close();
        }
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
        }
      });
    },
    // 停用门店
    blockups(val) {
      var that = this;
      this.$confirm("是否确定停用？如确定，该商户的支付将停用", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          blockup({}, val).then(res => {
            console.log(res);
            if (res.code == 405) {
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            } else if (res.code == 200) {
              this.$message({
                message: "已停用",
                type: "success"
              });
              this.refresh();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // 注销门店
    merchantremove(val) {
      this.$confirm("是否确定注销？如确定，该商户将被移除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          merchantremove({}, val).then(res => {
            console.log(res);
            if (res.code == 405) {
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            } else if (res.code == 200) {
              this.$message({
                message: "已注销",
                type: "success"
              });
              this.refresh();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // 启用商户
    merchantenable(val) {
      merchantenable({}, val).then(res => {
        console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else if (res.code == 200) {
          this.$message({
            message: "已启用",
            type: "success"
          });
          this.refresh();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 新增门店
    addmerchants(){
      this.$router.push({ path: "/addmerchants",
          query: { 
                // no: val,
            } 
      });
    }
  }
};
</script>
<style scoped>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #374459;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
}
.statistical > .statisticalitem {
  width: 50%;
  text-align: center;
  line-height: 200%;
}
.tableBox {
  margin-top: 20px;
}
.servicename {
  width: 60%;
}
.servicelevel {
  width: 20%;
}
.BDname {
  width: 20%;
}
.red {
  color: #f9607d;
}
.green{
  color: green;
}
</style>